﻿using System;
using UnityEngine;

namespace DiverseStudents.UI
{
    internal static class UIExtensions
    {
        public static T FindComponent<T>(this GameObject @object, string path = "") 
        {
            if (@object == null)
            {
                return default;
            }
            var tf = @object.transform;
            if (path.Length > 0)
            {
                try
                {
                    tf = tf.Find(path);
                }
                catch (Exception)
                {
                    DLog.Error("Find path error");
                }
            }
            T ans = tf.gameObject.GetComponent<T>();
            if (ans != null)
            {
                return ans;
            }
            else
            {
                DLog.Warring($"Not find path {path}");
            }
            return default;
        }

       public static  Sprite Clone(this Sprite sprite)
        {
            int width = (int)sprite.rect.width;
            int height = (int)sprite.rect.height;
            RenderTexture renderTexture = RenderTexture.GetTemporary(width, height, 0,RenderTextureFormat.Default,RenderTextureReadWrite.Linear );
            Graphics.Blit(sprite.texture, renderTexture);
            Texture2D readableText = new Texture2D(width, height);
            //RenderTexture previous = RenderTexture.active;
            //RenderTexture.active = renderTexture;
            readableText.ReadPixels(new Rect(0,0,width,height), 0, 0);
            readableText.Apply();
            RenderTexture.ReleaseTemporary(renderTexture);
            //RenderTexture.active = previous;
            Sprite sprite1 = Sprite.Create(readableText,sprite.rect,sprite.pivot);
            return sprite1;
        }

    }


}
